package cn.tedu.weibo.controller;

import cn.tedu.weibo.mapper.UserMapper;
import cn.tedu.weibo.pojo.dto.UserLoginDto;
import cn.tedu.weibo.pojo.dto.UserRegDto;
import cn.tedu.weibo.pojo.entity.User;
import cn.tedu.weibo.pojo.vo.UserVo;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpSession;

@RestController
public class UserController {
    @Autowired
    UserMapper mapper;

    //处理注册请求
    @RequestMapping("/reg")
    public int reg(@RequestBody UserRegDto userRegDto) {
        UserVo u = mapper.selectByUsername(userRegDto.getUsername()); //通过用户输入的用户名查询数据库里面的用户对象
        if (u != null) {
            return 2; //代表用户已存在
        }
        User user = new User();
        BeanUtils.copyProperties(userRegDto, user); //把dto里面的数据装进user
        mapper.insert(user);
        return 1; //注册成功
    }

    //处理登录请求
    @RequestMapping("/login")
    public int login(@RequestBody UserLoginDto userLoginDto, HttpSession session) {
        UserVo user = mapper.selectByUsername(userLoginDto.getUsername());
        if (user != null) {
            if (user.getPassword().equals(userLoginDto.getPassword())) {
                session.setAttribute("user", user); //把当前登录成功的用户对象保存进会话对象里面
                return 1; //登录成功
            }
            return 2; //密码错误
        }
        return 3; //用户名不存在
    }

    //处理获得当前登录的用户对象请求
    @RequestMapping("/currentUser")
    public UserVo currentUser(HttpSession session) {
        return (UserVo) session.getAttribute("user"); //从当前客户端对应的会话对象中取出登录成功时保存的用户对象
    }

    //处理退出登录请求
    @RequestMapping("/logout")
    public void logout(HttpSession session) {
        session.removeAttribute("user"); //删除会话对象中的user
    }
}
